home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 907 < prev    next >
Encoding:
Text File  |  1996-08-06  |  1.1 KB  |  60 lines

  1. Path: cea.fr!usenet
  2. From: Xavier Tarrago <tarrago@lcus15.saclay.cea.fr>
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: How to print a enum variable's names
  5. Date: 8 Jan 1996 09:11:55 GMT
  6. Organization: CEA Commissariat a l'Energie Atomique, France.
  7. Message-ID: <4cqn4r$9mp@news.cea.fr>
  8. References: <4cjohq$k5u@lsi.lsil.com>
  9. NNTP-Posting-Host: lcus15.saclay.cea.fr
  10.  
  11. song@lsil.com (Song Liang) wrote:
  12. >
  13. >   Suppose you have a variable foo of type "enum bar_type {CAR TRUCK VAN}", if 
  14. > you do "cout << foo", it will print either 0, 1 or 2.  Is there a simple trick
  15. > to print the names, i.e CAR, TRUCK or VAN?
  16.  
  17. #include <iostream.h>
  18. enum CarType {
  19.    VAN,
  20.    TRUCK,
  21.    CAR
  22. };
  23.  
  24. ostream& operator<<( ostream& os, CarType ct)
  25. {
  26.    switch( ct){
  27.    case VAN :
  28.       os << "VAN";
  29.       break;
  30.  
  31.    case TRUCK :
  32.       os << "TRUCK";
  33.       break;
  34.  
  35.    case CAR :
  36.       os << "CAR";
  37.       break;
  38.  
  39.    default:
  40.       os << "Unknown Car Type";
  41.       break;
  42.    }
  43.    return os;
  44. }
  45.  
  46. void main()
  47. {
  48.    CarType ct;
  49.    ct = VAN;
  50.    cout << "Type " << ct << " Valeur " << (int)ct << '\n';
  51.    return;
  52. }
  53.  
  54. result (HP C++):
  55. Type VAN Valeur 0
  56.  
  57.   Hope it helps
  58.    X.Tarrago
  59.